package com.st.config;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>title: com.wfx.config</p>
 * author zhuximing
 * description:
 */
@Component
@ServerEndpoint("/websocket/{id}")
public class WebSocketServer {


    //定义一个(线程安全的)map，存储客户端的会话
    private static ConcurrentHashMap<String,Session> sessions = new ConcurrentHashMap();

    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session){

        System.out.println("已经与客户端建立连接");
        //当前端建立连接，存储会话信息
        sessions.put(id,session);
    }



    @OnClose
    public void onClose(@PathParam("id") String id){
        System.out.println("与客户端关闭了连接 bye bye");
        sessions.remove(id);

    }


    //定义发送消息的静态方法
    public static void sendMessageToClient(String id,String message) throws  Exception{
        Session session = sessions.get(id);
        session.getBasicRemote().sendText(message);
    }
}